package com.sgb.member.ui.fragment;

import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sgb.member.PickCateType;
import com.sgb.member.R;
import com.sgb.member.databinding.FragmentMemberInviteOrApplyBinding;
import com.sgb.member.di.DaggerMemberFragComponent;
import com.sgb.member.di.MemberFragModule;
import com.sgb.member.entity.ApprovalRecordBean;
import com.sgb.member.entity.MemberAuditBean;
import com.sgb.member.entity.QualityMemberBean;
import com.sgb.member.ui.activity.MemberApplyJoinActivity;
import com.sgb.member.ui.activity.MemberApprovalActivity;
import com.sgb.member.ui.activity.MemberInviteJoinActivity;
import com.sgb.member.ui.activity.MemberInviteOrApplyActivity;
import com.sgb.member.ui.adapter.MemberApprovalRecordAdapter;
import com.sgb.member.view_model.MemberInviteOrApplyApprovalModel;
import com.sgb.member.weight.MemberCommonDialog;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.MemberStatusView;
import com.swgk.core.xrecyclerview.LoadingMoreFooter;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 审批记录
 */
public class MemberInviteOrApplyApprovalFragment extends AppLazyFragment implements MemberStatusView.OnChooseListener {

    @Inject
    MemberInviteOrApplyApprovalModel sModel;
    private FragmentMemberInviteOrApplyBinding mBinding;
    private int mCurPage;
    private String mTripStr; // 请选择需要邀请的企业
    private String mApproveType; // 邀请加盟审批类型 inviteJoinCompany 申請加盟审批类型 applyJoinCompany
    private QualityMemberBean qualityMemberBean;
    private MemberApprovalRecordAdapter mAdapter;

    private String mApprovalNo;
    private String mAreaNo;

    public static MemberInviteOrApplyApprovalFragment newInstance(int type) {
        MemberInviteOrApplyApprovalFragment fragment = new MemberInviteOrApplyApprovalFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("INDEX_PAGE", type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMemberFragComponent.builder()
                .appComponent(appComponent)
                .memberFragModule(new MemberFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_member_invite_or_apply, container, false);
        mBinding.setLifecycleOwner(this);
        return mBinding.getRoot();
    }

    @Override
    protected void initView() {
        assert getArguments() != null;
        mCurPage = getArguments().getInt("INDEX_PAGE", 0);
        mBinding.inviteSizeLayout.setVisibility(View.GONE);
        mBinding.tvChooseMember.setText(Html.fromHtml(String.format(getResources().getString(R.string.select_apply_member), "")));
        mBinding.tvInviteJoin.setOnClickListener(this);
        switch (mCurPage) {
            case 0:
                mBinding.tvInviteJoin.setText("邀请加盟");
                mTripStr = "请选择需要邀请的企业";
                mApproveType = "inviteJoinCompany";
                break;
            case 1:
                mBinding.tvInviteJoin.setText("申请加盟");
                mTripStr = "请选择需要申请的企业";
                mApproveType = "applyJoinCompany";
                break;
        }
        initPopup();
        initRecycler();
    }

    @Override
    protected void onLazyLoad() {
        loadData(false);
        sModel.getInviteOrApplyStatus(PickCateType.TYPE_0);
        sModel.getAddressModel(PickCateType.TYPE_1);
    }

    public void loadData(boolean isLoadMore) {
        String searchText = "";
        if (getActivity() != null) {
            searchText = ((MemberInviteOrApplyActivity) getActivity()).getSearchText();
        }
        if (!isLoadMore) {
            mBinding.tvChooseMember.setText(Html.fromHtml(String.format(getResources().getString(R.string.select_apply_member), "")));
        }
        sModel.getInviteOrApplyCompanyList(mCurPage, isLoadMore, searchText, mApprovalNo, mAreaNo);
    }

    @Override
    public void onMultiClick(View v) {
        if (v == mBinding.tvInviteJoin) {
            // 跳转邀请加盟申请页
            if (qualityMemberBean != null) {
                String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
                sModel.getProcessStatus(companyNo, mApproveType);
            } else {
                MToast.showToast(getContext(), mTripStr);
            }
        }
    }

    // 更新审批回调处理
    public void updateProcessStatus(String status) {
        // 有审批时：弹出审批确认弹窗，具体如原型所示，点击去填写跳转到邀请审批信息填写页
        // 无审批时：点击去填写跳转到邀请信息填写页
        if (status.equals("1")) {
            MemberCommonDialog dialog = new MemberCommonDialog(new MemberCommonDialog.SimpleListener() {
                @Override
                public void onPositive(Object... objects) {
                    // 跳转填写审批信息// 审批类型 1 申请加盟(固定传1就行) 2邀请加盟
                    jumpJoinPage();
                }
            }, MemberCommonDialog.STYLE_INVITE_JOIN);
            dialog.show(getActivity(), "MemberCommonDialog");
        } else {
            jumpJoinPage();
        }
    }

    private void jumpJoinPage() {
        // 跳转邀请加盟申请页
        switch (mCurPage) {
            case 0: // 邀请加盟
                MemberInviteJoinActivity.startAgain(getActivity(), qualityMemberBean, false);
                break;
            case 1: // 申请加盟
                //跳转到申请加盟界面 , 个人没有审批 直接跳转
                MemberApplyJoinActivity.startAgain(getActivity(), qualityMemberBean, false);
                break;
        }
    }

    private void initPopup() {
        mBinding.popApprovalStatus.setVisibility(View.VISIBLE);
        mBinding.popAddress.setVisibility(View.VISIBLE);
        mBinding.popApprovalStatus.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.popAddress.initPopup(mBinding.grayLayout, mBinding.popLine, this);
    }

    @Override
    public void onLoadChooseData(String mKeyName) {
        switch (mKeyName) {
            case "审批状态":
                sModel.getInviteOrApplyStatus(PickCateType.TYPE_0);
                break;
            case "区域":
                sModel.getAddressModel(PickCateType.TYPE_1);
                break;
        }
    }

    public void setChooseItemData(int type, List<CommonPopEntity> data) {
        if (data == null || data.size() == 0) return;
        switch (type) {
            case PickCateType.TYPE_0:
                mBinding.popApprovalStatus.setData(data);
                break;
            case PickCateType.TYPE_1:
                mBinding.popAddress.setData(data);
                break;
        }
    }

    @Override
    public void onChooseResult(String mKeyName, CommonPopEntity entity, Object... objects) {
        int position = (int) objects[0];
        String no = position == 0 ? "" : entity.getNo();
        String id = position == 0 ? "" : entity.getId();
        switch (mKeyName) {
            case "审批状态":
                if (!TextUtils.equals(id, mApprovalNo)) {
                    mApprovalNo = id;
                    loadData(false);
                }
                break;
            case "区域":
                if (!TextUtils.equals(no, mAreaNo)) {
                    mAreaNo = no;
                    loadData(false);
                }
                break;
        }
    }

    /**
     * -------------------------------------initRecycler------------------------------------------
     */
    private void initRecycler() {
        TextView textView = mBinding.empView.findViewById(R.id.no_data_count);
        textView.setVisibility(View.VISIBLE);
        mBinding.recyclerView.setPullRefreshEnabled(true);
        mBinding.recyclerView.setLoadingMoreEnabled(true);
        LoadingMoreFooter footer = (LoadingMoreFooter) mBinding.recyclerView.getFootView();
        footer.setNoMoreHint("已经到底啦~");
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData(false);
            }

            @Override
            public void onLoadMore() {
                loadData(true);
            }
        });
        initRecyclerAdapter();
    }

    private void initRecyclerAdapter() {
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new MemberApprovalRecordAdapter(getContext(), new ArrayList<>(), mCurPage) {
            @Override
            protected void againInvite(ApprovalRecordBean entity) {
                qualityMemberBean = new QualityMemberBean();
                qualityMemberBean.setNo(entity.getNo());
                qualityMemberBean.setCompanyName(entity.getBusinessName());
                qualityMemberBean.setCompanyNo(entity.getBusinessNo());
                qualityMemberBean.setAddress(entity.getAddr());
                qualityMemberBean.setProcessId(entity.getProcessId());
                qualityMemberBean.setProvinceNo(entity.getProvinceNo());
                qualityMemberBean.setCityNo(entity.getCityNo());
                qualityMemberBean.setDistrictNo(entity.getAreaNo());
                String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
                sModel.getProcessStatus(companyNo, mApproveType);
            }
        };
        mAdapter.setOnItemClick(new AdapterOnItemClick<ApprovalRecordBean>() {
            @Override
            public void onItemClick(ApprovalRecordBean memberBean, int position) {
                switch (mCurPage) {
                    case 0: // 邀请加盟记录
                    case 1: // 申请加盟记录
                        sModel.getUrlSetting(memberBean, "approvalDetail");
                        break;
                }
            }
        });
        mBinding.recyclerView.setAdapter(mAdapter);
    }

    public void closeRecyclerRefreshing() {
        mBinding.recyclerView.refreshComplete();
        mBinding.recyclerView.loadMoreComplete();
    }

    public void showEmpty() {
        mAdapter.clearDatas();
        mBinding.empView.setVisibility(View.VISIBLE);
    }

    public void refreshRecycler(List<ApprovalRecordBean> list, boolean isLoadMore, boolean noMoreData) {
        closeRecyclerRefreshing();
        mBinding.recyclerView.setVisibility(View.VISIBLE);
        mBinding.recyclerView.setLoadingMoreEnabled(!noMoreData);
        if (isLoadMore) {
            if (list != null && list.size() > 0) {
                mAdapter.addDatas(list);
            }
        } else {
            if (list != null && list.size() > 0) {
                mBinding.empView.setVisibility(View.GONE);
                mAdapter.setDatas(list);
            } else {
                mAdapter.clearDatas();
                mBinding.empView.setVisibility(View.VISIBLE);
            }
        }
    }
}
